#include "exchange_access_token_command.h"
#include "service/backend_service.h"
#include "command_executor.h"
#include <QDebug>
#include <QUrl>
#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>
#include <QStandardPaths>
#include <QDir>
#include <QSettings>
#include <QFile>
#include <QNetworkReply>

ExchangeAccessTokenCommand::ExchangeAccessTokenCommand(QObject *parent)
    : BaseCommand(parent)
{
}

ExchangeAccessTokenCommand::~ExchangeAccessTokenCommand()
{
}

void ExchangeAccessTokenCommand::setNetworkAccessManager(QNetworkAccessManager *networkManager)
{
    // 如果之前已经设置了 networkManager，先断开旧的连接
    if (m_networkManager) {
        disconnect(m_networkManager, &QNetworkAccessManager::finished,
                   this, &ExchangeAccessTokenCommand::handleExchangeAccessTokenResponse);
    }
    
    BaseCommand::setNetworkAccessManager(networkManager);
    
    // 连接网络请求完成信号
    if (m_networkManager) {
        connect(m_networkManager, &QNetworkAccessManager::finished,
                this, &ExchangeAccessTokenCommand::handleExchangeAccessTokenResponse);
    }
}

bool ExchangeAccessTokenCommand::execute()
{
    if (!isValid()) {
        qDebug() << "ExchangeAccessTokenCommand: BackendService 或 QNetworkAccessManager 未设置";
        emit exchangeAccessTokenCompleted(-1, "BackendService 或 QNetworkAccessManager 未设置", "");
        return false;
    }
    
    // 从 BackendService 获取 domainId
    QString domainId;
    if (m_backendService) {
        domainId = m_backendService->loadSelectedCompanyId();
    }
    
    if (domainId.isEmpty()) {
        qDebug() << "ExchangeAccessTokenCommand: 无法获取公司ID";
        emit exchangeAccessTokenCompleted(-1, "无法获取公司ID", "");
        return false;
    }
    
    // 获取 baseUrl
    QString baseUrl = getBaseUrl();
    
    // 构建请求URL
    QString url = buildRequestUrl(baseUrl);
    
    qDebug() << "ExchangeAccessTokenCommand: 发送获取AccessToken请求到:" << url;
    qDebug() << "ExchangeAccessTokenCommand: domainId:" << domainId;
    
    // 获取 checkInToken（从 BackendService 或设置文件）
    QString checkInToken;
    if (m_backendService) {
        // 尝试从 BackendService 获取 checkInToken
        // 注意：BackendService 的 loadCheckInToken 是私有方法，我们需要从设置文件读取
        QString homePath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
        if (!homePath.isEmpty()) {
            QString settingsPath = QDir(homePath).filePath(".myapps/setting.ini");
            if (QFile::exists(settingsPath)) {
                QSettings settings(settingsPath, QSettings::IniFormat);
                checkInToken = settings.value("Auth/CheckInToken", "").toString();
            }
        }
    }
    
    if (checkInToken.isEmpty()) {
        qDebug() << "ExchangeAccessTokenCommand: 没有可用的checkInToken";
        emit exchangeAccessTokenCompleted(-1, "没有可用的checkInToken", "");
        return false;
    }
    
    // 创建网络请求
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    
    // 构建请求体
    QJsonObject requestBody;
    requestBody["checkInToken"] = checkInToken;
    requestBody["domainId"] = domainId;
    
    QJsonDocument doc(requestBody);
    QByteArray data = doc.toJson();
    
    qDebug() << "ExchangeAccessTokenCommand: 请求体:" << data;
    
    // 发送POST请求（异步）
    QNetworkReply *reply = m_networkManager->post(request, data);
    if (!reply) {
        qDebug() << "ExchangeAccessTokenCommand: 创建网络请求失败";
        emit exchangeAccessTokenCompleted(-1, "创建网络请求失败", "");
        return false;
    }
    
    qDebug() << "ExchangeAccessTokenCommand: 发送获取AccessToken请求，reply对象:" << reply;
    
    // 设置用户数据，用于识别请求类型
    reply->setProperty("requestType", "exchangeAccessToken");
    
    // 异步操作，立即返回
    return true;
}

void ExchangeAccessTokenCommand::handleExchangeAccessTokenResponse(QNetworkReply *reply)
{
    // 检查对象是否仍然有效（可能在信号排队期间被销毁）
    if (!isValid()) {
        qDebug() << "ExchangeAccessTokenCommand: 对象已被销毁，忽略响应";
        if (reply) {
            reply->deleteLater();
        }
        return;
    }
    
    if (!reply) {
        qDebug() << "ExchangeAccessTokenCommand: 交换AccessToken响应为空";
        // 只有在对象仍然有效时才发送信号
        if (isValid()) {
            emit exchangeAccessTokenCompleted(-1, "交换AccessToken响应为空", "");
        }
        return;
    }
    
    QString requestType = reply->property("requestType").toString();
    if (requestType != "exchangeAccessToken") {
        // 不是交换AccessToken请求，忽略
        reply->deleteLater();
        return;
    }
    
    // 再次检查对象是否仍然有效
    if (!isValid()) {
        qDebug() << "ExchangeAccessTokenCommand: 对象已被销毁，忽略响应";
        reply->deleteLater();
        return;
    }
    
    // 检查网络错误
    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "ExchangeAccessTokenCommand: 获取AccessToken网络请求错误:" << reply->errorString();
        // 只有在对象仍然有效时才发送信号
        if (isValid()) {
            emit exchangeAccessTokenCompleted(-1, "网络请求失败: " + reply->errorString(), "");
        }
        reply->deleteLater();
        return;
    }
    
    // 读取响应数据
    QByteArray responseData = reply->readAll();
    qDebug() << "ExchangeAccessTokenCommand: 获取AccessToken响应数据包:" << responseData;
    
    // 解析JSON响应
    QJsonParseError parseError;
    QJsonDocument responseDoc = QJsonDocument::fromJson(responseData, &parseError);
    
    if (parseError.error != QJsonParseError::NoError) {
        qDebug() << "ExchangeAccessTokenCommand: 获取AccessToken JSON解析错误:" << parseError.errorString();
        // 只有在对象仍然有效时才发送信号
        if (isValid()) {
            emit exchangeAccessTokenCompleted(-1, "JSON解析失败: " + parseError.errorString(), "");
        }
        reply->deleteLater();
        return;
    }
    
    if (!responseDoc.isObject()) {
        qDebug() << "ExchangeAccessTokenCommand: 获取AccessToken响应不是有效的JSON对象";
        // 只有在对象仍然有效时才发送信号
        if (isValid()) {
            emit exchangeAccessTokenCompleted(-1, "响应格式错误", "");
        }
        reply->deleteLater();
        return;
    }
    
    // 最后一次检查对象是否仍然有效
    if (!isValid()) {
        qDebug() << "ExchangeAccessTokenCommand: 对象已被销毁，忽略响应解析";
        reply->deleteLater();
        return;
    }
    
    QJsonObject response = responseDoc.object();
    int resultCode = response["resultCode"].toInt();
    QString msg = response["msg"].toString();
    
    if (resultCode == 0) {
        // 成功获取AccessToken
        QString accessToken = response["accessToken"].toString();
        
        if (!accessToken.isEmpty()) {
            qDebug() << "ExchangeAccessTokenCommand: 成功获取AccessToken:" << accessToken;
            
            // 保存 accessToken 到 BackendService
            saveAccessToken(accessToken);
            
            // 发送完成信号（保持兼容性）
            emit exchangeAccessTokenCompleted(resultCode, msg, accessToken);
        } else {
            qDebug() << "ExchangeAccessTokenCommand: 获取AccessToken响应中没有accessToken字段";
            emit exchangeAccessTokenCompleted(-1, "响应中没有accessToken字段", "");
        }
    } else {
        qDebug() << "ExchangeAccessTokenCommand: 获取AccessToken失败:" << msg;
        emit exchangeAccessTokenCompleted(resultCode, msg, "");
    }
    
    reply->deleteLater();
}

QString ExchangeAccessTokenCommand::buildRequestUrl(const QString &baseUrl)
{
    return baseUrl + "/signon/api/login/exchangeAccessToken";
}

void ExchangeAccessTokenCommand::saveAccessToken(const QString &accessToken)
{
    // 通过 CommandExecutor 的静态方法保存 accessToken
    CommandExecutor::setAccessToken(accessToken);
    qDebug() << "ExchangeAccessTokenCommand: accessToken 已保存到 CommandExecutor";
}

